
const { ccclass, property } = cc._decorator;

@ccclass
export default class Rocker extends cc.Component {


    public joyEnd = false;

    @property(cc.Node)
    public ball: cc.Node = null;

    private root: cc.Node;

    private circleRadius: number = 60.5;

    private ballRadius: number = 35;

    start() {

        this.root = cc.Canvas.instance.node;

        this.root.on("touchstart", this.onTouchStart, this);
        this.root.on("touchmove", this.onTouchMove, this);
        this.root.on("touchend", this.onTouchEnd, this);

        this.node.active = false;

    }

    onTouchStart(e: cc.Event.EventTouch): void {
        this.node.active = true;

        let p2 = this.node.parent.convertToNodeSpaceAR(e.getLocation());

        this.node.x = p2.x;
        this.node.y = p2.y;

    }

    onTouchMove(e: cc.Event.EventTouch): void {

        let p2 = this.node.parent.convertToNodeSpaceAR(e.getLocation());

        let angle: number = Math.atan2(p2.y - this.node.y, p2.x - this.node.x);

        let distance = cc.Vec2.distance<cc.Vec2>(new cc.Vec2(this.node.x, this.node.y), p2);

        if (distance <= (this.circleRadius - this.ballRadius)) {
            this.ball.x = p2.x - this.node.x;
            this.ball.y = p2.y - this.node.y;
        } else {
            this.ball.x = Math.cos(angle) * (this.circleRadius - this.ballRadius);
            this.ball.y = Math.sin(angle) * (this.circleRadius - this.ballRadius);
            this.node.active = true;

        }
        if (this.node.active == false)
            return;
    }

    onTouchEnd(e: cc.Event.EventTouch): void {
        this.node.active = false;
    }

    onDestroy() {
        super.destroy();
        this.root.off("touchstart", this.onTouchStart, this);
        this.root.off("touchmove", this.onTouchMove, this);
        this.root.off("touchend", this.onTouchEnd, this);
    }

}
